package com.fast.aop;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class WebLogHandler {

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void webLog() {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        //打印出参
        log.info("Response Args : {}", result);
        //执行耗时
        log.info("exe-time      : {} ms", System.currentTimeMillis() - startTime);
        log.info("============================================End==================================================="+System.lineSeparator());
        return result;
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        String msg = annotation.value();
        log.info(System.lineSeparator());
        log.info("============================================Start=================================================");
        //打印请求的url
        log.info("URL           : {}",request.getRequestURL().toString());
        log.info("Description   : {}",msg);
        log.info("HTTP Method   : {}",request.getMethod());
        log.info("Class Method  : {},{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
        log.info("IP            : {}",request.getRemoteAddr());
        Object[] args = joinPoint.getArgs();
        log.info("Request Args  : {}",args);
    }

    @After("webLog()")
    public void doAfter() throws Throwable{
        log.info("==========================================Response=================================================");
    }
}
